package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryShopById(Long id) {
        String cacheShopKey = RedisConstants.CACHE_SHOP_KEY;
        String cacheShopStr = stringRedisTemplate.opsForValue().get(cacheShopKey);
        if (StrUtil.isNotBlank(cacheShopStr)) {
            return Result.ok(JSONUtil.toBean(cacheShopStr, Shop.class));
        }
        Shop shop = getById(id);
        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        stringRedisTemplate.opsForValue().set(cacheShopKey, JSONUtil.toJsonPrettyStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }
}
